package com.travel.travel_springboot_web.controller;

import com.travel.travel_springboot_web.entity.Banner;
import com.travel.travel_springboot_web.service.BannerService;
import com.travel.travel_springboot_web.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/banner")
@CrossOrigin
public class BannerController {
    
    private static final Logger logger = LoggerFactory.getLogger(BannerController.class);
    
    @Autowired
    private BannerService bannerService;
    
    @Autowired
    private FileUtil fileUtil;
    
    @GetMapping("/list")
    public Map<String, Object> list() {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("Getting banner list from goods_images");
            List<Banner> banners = bannerService.getAllActiveBanners();
            
            // 添加完整的URL
            banners.forEach(banner -> {
                String imageUrl = banner.getImageUrl();
                if (!imageUrl.startsWith("http")) {
                    banner.setImageUrl("http://localhost:8080" + imageUrl);
                }
            });
            
            logger.info("Found {} banners", banners.size());
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", banners);
        } catch (Exception e) {
            logger.error("Error getting banner list: ", e);
            result.put("code", 500);
            result.put("message", "Error: " + e.getMessage());
        }
        return result;
    }
    
    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            String fileUrl = fileUtil.saveFile(file);
            logger.info("Banner uploaded: {}", fileUrl);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", fileUrl);
        } catch (Exception e) {
            logger.error("Banner upload failed: ", e);
            result.put("code", 500);
            result.put("message", "Error: " + e.getMessage());
        }
        return result;
    }
} 